package com.ews.onlineexchange.service.schedule;

import java.util.Calendar;
import java.util.Date;

import javax.annotation.Resource;
import javax.ejb.Schedule;
import javax.ejb.ScheduleExpression;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.ejb.TimerConfig;
import javax.ejb.TimerService;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.inject.Inject;
import javax.persistence.EntityManager;

import org.hibernate.CacheMode;
import org.hibernate.FlushMode;
import org.hibernate.Query;
import org.hibernate.ScrollMode;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;

import com.ews.onlineexchange.model.QualificationCert;
import com.ews.onlineexchange.model.RejectRecord;

@Singleton
@Startup
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class CertValidateTimer {

	@Resource
	TimerService timerService;
	
	@Inject
	EntityManager entityManager;
	
//	@PostConstruct
	public void init() {
		ScheduleExpression schedule = new ScheduleExpression();	
		schedule.hour(2);
		timerService.createCalendarTimer(schedule, new TimerConfig("certValidatorTimer", false));
		
//		check();
	}
	
	private static final String QUERY_ALL_VALID_CERT_EQL = ""
			+ "	SELECT			cert"
			+ "	FROM			QualificationCert cert "
			+ "	WHERE			cert.valid = true 	";
//	@Timeout
	@Schedule(hour="2", minute="0", second="0", info = "certValidatorTimer", persistent = false)
	public void check() {
		System.out.println("===================================================================");
		System.out.println("Cert Validate Timer Runned");
		System.out.println("===================================================================");
		Date now = new Date();
//		Calendar cal = Calendar.getInstance();
//		if (cal.get(Calendar.HOUR_OF_DAY) - 2 != 0)
//			return;
		
		Session session = entityManager.unwrap( Session.class );
		ScrollableResults sr = session.createQuery(QUERY_ALL_VALID_CERT_EQL).setCacheMode( CacheMode.IGNORE )
		        .scroll( ScrollMode.FORWARD_ONLY );
		long count = 0L;
		
		while (sr.next()) {
			QualificationCert cert = (QualificationCert) sr.get(0);
			if(null == cert.getAllotedDate()) continue;
			if (cert.getAllotedDate().before(now)) {
				cert.setValid(false);
				cert.setAuditResult(false);
				RejectRecord rejectRecord = new RejectRecord();
				rejectRecord.setReason("资质有效期已过!");
				cert.setCurrRejectRecord(rejectRecord);
				cert.getHistoryRejectRecords().add(rejectRecord);
				session.update(cert);
			}
			count++;
			if (count % 200 == 0) {
				session.flush();
			}
		}
		session.flush();
	}
}
